package org.ragdollcat.first.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.ragdollcat.first.exception.BusinessException;
import org.ragdollcat.first.exception.ErrorCode;
import org.ragdollcat.first.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

/**
 * url文件上传
 */
@Service
@Slf4j
public class UrlFileUpload extends AbsFileUpload {
    /**
     * 处理文件来源
     *
     * @param source
     * @param file
     */
    @Override
    protected void processFile(Object source, File file) {
        String url = (String) source;
        HttpUtil.downloadFile(url, file);
    }

    /**
     * 校验参数
     *
     * @param source
     */
    @Override
    protected void vaildParams(Object source) {
        String url = (String) source;
        //校验非空
        ThrowUtils.throwIf(StrUtil.isBlank(url), ErrorCode.PARAMS_ERROR, "url地址不能为空");
        //校验url的格式
        try {
            new URL(url);
        } catch (MalformedURLException e) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "url格式非法");
        }
        //校验url的协议
        ThrowUtils.throwIf(!url.startsWith("http://") && !url.startsWith("https://"), ErrorCode.PARAMS_ERROR, "url协议非法");

        HttpResponse httpResponse = null;
        try {
            //发送head请求查看文件是否存在
            httpResponse = HttpUtil.createRequest(Method.HEAD, url).execute();
            if (!httpResponse.isOk()) {
                return;
            }
            String header = httpResponse.header("Content-Type");
            if (StrUtil.isNotBlank(header)) {
                //校验文件类型
                final List<String> ALLOW_CONTENT_TYPES = Arrays.asList("image/jpeg", "image/jpg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPES.contains(header.toLowerCase()),
                        ErrorCode.PARAMS_ERROR, "文件类型错误");

                // 校验文件大小
                String contentLengthStr = httpResponse.header("Content-Length");
                if (StrUtil.isNotBlank(contentLengthStr)) {
                    try {
                        long contentLength = Long.parseLong(contentLengthStr);
                        final long TWO_MB = 2 * 1024 * 1024L; // 限制文件大小为 2MB
                        ThrowUtils.throwIf(contentLength > TWO_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过 2M");
                    } catch (NumberFormatException e) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "文件大小格式错误");
                    }
                }
            }
        } finally {
            if (ObjUtil.isNotEmpty(httpResponse)) {
                httpResponse.close();
            }
        }

    }

    /**
     * 得到原始文件名
     *
     * @param source
     * @return
     */
    @Override
    protected String getOriginalFilename(Object source) {
        String url = (String) source;
        return FileUtil.mainName(url);
    }


}
